<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card>
        <!-- 放置表单 -->
        <el-form
          ref="userForm"
          label-width="120px"
          :model="userInfo"
          :rules="rules"
          style="margin-left: 120px; margin-top: 30px"
        >
          <el-form-item label="姓名:" prop="username">
            <el-input v-model="userInfo.username" style="width: 300px" />
          </el-form-item>
          <el-form-item label="手机">
            <el-input v-model="userInfo.mobile" disabled style="width: 300px" />
          </el-form-item>

          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker
              v-model="userInfo.timeOfEntry"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="员工头像">
            <upload-img ref="img" v-model="userInfo.staffPhoto" />
          </el-form-item>

          <!-- 保存个人信息 -->
          <el-row class="inline-info" type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" @click="confirm">保存更新</el-button>
              <el-button @click="$router.back()">返回</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script>

// 引入获取用户回显接口
import { getUserDetailById, saveUserDetailById } from '@/api/user'

export default {
  name: 'Detail',
  data() {
    return {
      userInfo: {},
      rules: {
        username: [{ trigger: 'blur', required: true, message: '员工名为必填项' }],
        timeOfEntry: [{ trigger: 'blur', required: true, message: '员工入职时间为必填项' }]
      }
    }
  },
  created() {
    // 掉方法获取数据
    this.getUserDataFn()
  },
  methods: {
    // 点击确定触发的事件
    confirm() {
      // 兜底校验
      this.$refs.userForm.validate(async(val) => {
        if (val) {
          if (this.$refs.img.flag) {
            // 掉接口更新员工数据
            await saveUserDetailById(this.userInfo)

            // 掉接口更新首页头像
            this.$store.dispatch('user/asyncSetUserInfo')

            // 给出提示
            this.$message({
              type: 'success',
              message: '操作成功'
            })

            // 跳转到之前页面
            this.$router.back()
          } else {
            // 给出提示
            this.$message({
              type: 'warning',
              message: '操作失败'
            })
          }
        }
      })
    },
    // 获取用户信息方法
    async getUserDataFn() {
      // 掉接口获取数据
      const res = await getUserDetailById(this.$route.query.id)

      // 获取数据赋值给本地
      this.userInfo = res
    }
  }
}
</script>
